﻿using eLoan.Models;
using System;
using System.Linq;
using System.Web.Mvc;

namespace eLoan.Controllers
{
    public class BranchController : BaseController
    {
        public ActionResult AddEdit(string code)
        {
            try
            {
                CheckUserPageAccess(AdministrationHelper.UserPageAccess.Branches);

                var branchModel = new BranchModel();

                if (code == null)
                {
                    branchModel.DBCommand = AdministrationHelper.DBCommand.Add.ToString();

                    return View("AddEdit", branchModel);
                }
                else
                {
                    branchModel.DBCommand = AdministrationHelper.DBCommand.Edit.ToString();
                    
                    var branches = new DatabaseContext().Branches;
                    var branch = branches.Where(w => w.BranchCode == code);
                    if (branch.Any())
                        branchModel.Branch = branch.SingleOrDefault<Branch>();

                    return View("AddEdit", branchModel);
                }
            }
            catch (Exception ex)
            {
                return View("Error", ex);
            }
        }

        [HttpPost]
        public ActionResult Save(Branch branch, string command)
        {
            try
            {
                CheckUserPageAccess(AdministrationHelper.UserPageAccess.Branches);

                if (ModelState.IsValid)
                {
                    using (var db = new DatabaseContext())
                    {
                        if (command == AdministrationHelper.DBCommand.Add.ToString())
                        {
                            db.Branches.Add(branch);
                            db.SaveChanges();
                        }
                        else if (command == AdministrationHelper.DBCommand.Edit.ToString())
                        {
                            db.Entry(branch).State = System.Data.EntityState.Modified;
                            db.SaveChanges();
                        }
                        else
                        {
                            // cancelled
                        }
                    }
                }

                return RedirectToAction("Branches", "Administration");
            }
            catch (Exception ex)
            {
                return View("Error", ex);
            }
        }
    }
}
